package com.elm.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.elm.model.Food;
import com.elm.model.ShoppingCar;
import com.elm.model.User;
import com.elm.model.UserOrder;
import com.elm.service.SellerOrderService;
import com.elm.service.ShoppingCarService;
import com.elm.service.UserOrderService;
import com.elm.serviceimpl.SellerOrderServiceImp;
import com.elm.serviceimpl.ShoppingCarServiceImpl;
import com.elm.serviceimpl.UserOrderServiceImpl;

public class FirmOrderController extends HttpServlet{
	ShoppingCarService scservice = new ShoppingCarServiceImpl();
	UserOrderService uoservice = new UserOrderServiceImpl();
	SellerOrderService soservice = new SellerOrderServiceImp();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		req.setCharacterEncoding("utf8");
		HttpSession session = req.getSession();
		User user = (User) session.getAttribute("currentUser");
		//将份数更新的数更改到数据库
		List<ShoppingCar> carinfo = new ArrayList<ShoppingCar>();
		//得到购物车内的所有信息
		carinfo = (List<ShoppingCar>) session.getAttribute("carinfo");
		String fnumbers = req.getParameter("fnumber");
		String[] fnumber = fnumbers.split(",");
		scservice.changeNumFoods(fnumber, carinfo);
		//串接carsid
		String carsid = "";
		for (ShoppingCar shoppingCar : carinfo) {
			if(shoppingCar.getIsdel() == 0){
				if(carsid == ""){
					carsid = "" + shoppingCar.getCarid();
				}else {
					carsid = carsid + "," + shoppingCar.getCarid();
				}
			}
		}
		
		//插入当前订单
		uoservice.insertOrder(carsid, 1, user.getUserid());
		//求出订单中所有的orderid的最大
				List<UserOrder> alluorder = new ArrayList<UserOrder>();
				alluorder = uoservice.getAllOrders();
				int uorderidmax = 1;//存放userorderid最大值
				for (UserOrder userOrder : alluorder) {
					if(userOrder.getUserorderid() > uorderidmax){
						uorderidmax = userOrder.getUserorderid();
					}
				}
				//提交显示到商家订单
				List<Food> foods = new ArrayList<Food>();
				foods = (List<Food>) session.getAttribute("carfoods");
				int i = soservice.insertUorderToSellerOrder(uorderidmax, foods.get(0).getSellerid(), 2);
		//提交订单后，购物车清空
		scservice.emptyShoppingCar(user.getUserid());
	}
}
